import { ElMessage } from 'element-plus'
import { showToast } from 'vant'
import { Code, Platform } from './enums'

export default class R<T> {
    static SUCCESSCODES: (string | number)[] = [Code.SUCCESS]
    static WARNINGCODES: (string | number)[] = [800]
    static ERRORCODES: (string | number)[] = [Code.ERROR]
    static msgKey = 'msg'
    static platform: Platform = Platform.admin
    private _res: T
    code: Code
    msg: string = ''

    constructor(code: Code, res: T, msg = '') {
        R.platform = import.meta.env.VITE_APP_PLARTFORM

        this.code = code
        this.msg = msg || res[R.msgKey]
        this._res = res
    }

    private isValid() {

        if (this.SUCCESS) {
            return true
        }

        if (this.WARNING) {
            return false
        }

        if (this.ERROR) {
            switch (R.platform) {
                case Platform.h5:
                    showToast(this.msg)
                    break;
                case Platform.pc:
                case Platform.admin:
                    ElMessage.error(this.msg)
                    break;
                default:
                    break;
            }
            return false
        }

        return true
    }

    result(call?: (data: T) => void) {
        if (this.isValid()) {
            call && call(this._res)
            this._res['SUCCESS'] = R.SUCCESSCODES.includes(this.code)
            this._res['WARNING'] = R.WARNINGCODES.includes(this.code)
            this._res['ERROR'] = R.ERRORCODES.includes(this.code)
            return this._res
        }
        return this
    }

    get SUCCESS() {
        return R.SUCCESSCODES.includes(this.code)
    }

    get WARNING() {
        return R.WARNINGCODES.includes(this.code)
    }

    get ERROR() {
        return R.ERRORCODES.includes(this.code)
    }
}